package com.example.image

import android.content.Context
import android.net.Uri
import android.widget.ImageView
import com.example.image.loader.CustomImageLoader
import com.example.image.loader.FrescoImageLoader
import com.example.image.loader.GlideImageLoader
import com.example.image.loader.PicassoImageLoader
import com.example.image.loader.UniversalImageLoader
import java.io.File

class LoadImageManager constructor(private  val ctx:Context){
    private  var mOptions = ImageOptions.build()

    private var imageLoader:IImageLoader = GlideImageLoader()

    private  var mResource:Int? = 0
    private  var mUrl:String? = ""
    private  var mUri:Uri?=null
    private  var mFile:File?=null
    private  var mByteArray:ByteArray?=null

    private var resourceType = ResourceType.URL



    fun switchStrategy(strategy:ImageLoadStrategy): LoadImageManager {
        imageLoader = when(strategy){
            ImageLoadStrategy.GLIDE -> GlideImageLoader()
            ImageLoadStrategy.PICASSO -> PicassoImageLoader()
            ImageLoadStrategy.FRESCO -> FrescoImageLoader()
            ImageLoadStrategy.UNIVERSAL -> UniversalImageLoader()
            ImageLoadStrategy.CUSTOM -> CustomImageLoader()
        }
        return this
    }
    fun setOptions(options: ImageOptions): LoadImageManager {
        mOptions = options
        return this
    }

    fun loadFile(file:File):LoadImageManager{
        mFile = file
        resourceType = ResourceType.FILE
        return  this
    }
    fun loadUrl(url:String):LoadImageManager{
        mUrl = url
        resourceType = ResourceType.URL
        return  this
    }
    fun loadUri(uri:Uri):LoadImageManager{
        mUri = uri
        resourceType = ResourceType.URI
        return  this
    }
    fun loadResource(resId:Int):LoadImageManager{
        mResource = resId
        resourceType = ResourceType.RESOURCE
        return  this
    }
    fun loadByteArray(bytes:ByteArray):LoadImageManager{
        mByteArray = bytes
        resourceType = ResourceType.BYTEARRAY
        return  this
    }
//    fun loadUrl(url:String){
//        mUrl = url
//    }

    fun into(target:ImageView){
        when(resourceType){
            ResourceType.URL ->mUrl?.let { imageLoader.loadUrlIntoImageView(ctx, it, target, mOptions) }
            ResourceType.URI -> mUri?.let { imageLoader.loadUriIntoImageView(ctx, it, target, mOptions) }
            ResourceType.RESOURCE -> mResource?.let {imageLoader.loadResourceIntoImageView(ctx, it, target, mOptions)  }
            ResourceType.FILE ->mFile?.let {  imageLoader.loadFileIntoImageView(ctx, it, target, mOptions) }
            ResourceType.BYTEARRAY ->mByteArray?.let { imageLoader.loadByteArrayIntoImageView(ctx, it, target, mOptions)  }
        }

    }

    enum class ResourceType{
        FILE,URL,URI,RESOURCE,BYTEARRAY
    }
}
